package com.imooc.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUser;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Service;

/**
 * 
 * @author JZH
 * 
 * SpringSecurity通过UserDetailsService来获取用户信息
 */
@Service
public class MyUserDetailsService implements UserDetailsService, SocialUserDetailsService {

	private Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 用户名密码登陆
	 */
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		String password = getPassword(username);
		/*
		 * 参数3：enabled：是否被删除
		 * 参数4：accountNonExpired：是否过期
		 * 参数5：credentialsNonExpired：密码是否过期
		 * 参数6：accountNonLocked：是否被冻结
		 */
		return new User(username, password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}

	/**
	 * 第三方应用登陆
	 */
	@Override
	public SocialUserDetails loadUserByUserId(String userId) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		String password = getPassword(userId);
		logger.info("社交用户登陆ID：" + userId);
		return new SocialUser(userId, password, true, true, true, true, AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
	}

	
	private String getPassword(String key) {
		String password = "";
		switch(key) {
		case "qwert" :
			password = "111111";
			break;
		case "asdfg" :
			password = "222222";
			break;
		case "zxcvb" :
			password = "333333";
			break;
		case "rtyui" :
			password = "444444";
			break;
		case "13012345678" :
			password = "555555";
			break;
		default :
			break;
		}
		password = passwordEncoder.encode(password);
		logger.info("数据库中密码："+password);
		return password;
	}
}
